﻿using MediatR;
using S_Gridding.Domains.BasicData;
using S_Gridding.Infrastructure.Interface;
using S_Gridding.Read.Api.Command.AssemType;

namespace S_Gridding.Read.Api.CommandHands.AssemType
{
    /// <summary>
    /// 显示事件类型管理树形
    /// </summary>
    public class ShowTreeCommandHander : IRequestHandler<ShowTreeCommand, List<ShowTreeAssemDTO<AssemTypeInfo>>>
    {
        private readonly IDapperAssemTypeRepository _dapperAssemTypeRepository;

        public ShowTreeCommandHander(IDapperAssemTypeRepository dapperAssemTypeRepository)
        {
            _dapperAssemTypeRepository = dapperAssemTypeRepository;
        }
        public async Task<List<ShowTreeAssemDTO<AssemTypeInfo>>> Handle(ShowTreeCommand request, CancellationToken cancellationToken)
        {
            var sql = $"select * from AssemTypeInfo where Pid=@Pid";
            var query = await _dapperAssemTypeRepository.GetTree(request.Pid, sql);
            var treeInfo = new List<ShowTreeAssemDTO<AssemTypeInfo>>();
            foreach (var item in query)
            {
                var tree = new ShowTreeAssemDTO<AssemTypeInfo>
                {
                    value = item.AssemTypeId,
                    label = item.AssemTypeName,
                    pid = item.Pid,
                    children = null
                };
                treeInfo.Add(tree);
                await Getchildren(item.AssemTypeId, tree);
            }
            return await Task.FromResult(treeInfo);
        }

        public async Task Getchildren(int id, ShowTreeAssemDTO<AssemTypeInfo> tree)
        {
            var sql = "select * from AssemTypeInfo where Pid=@Pid";
            var query = await _dapperAssemTypeRepository.GetTree(id, sql);
            foreach (var item in query)
            {
                if(tree.children==null)
                {
                    tree.children = new List<ShowTreeAssemDTO<AssemTypeInfo>>();
                }
                var child = new ShowTreeAssemDTO<AssemTypeInfo>
                {
                    value = item.AssemTypeId,
                    label = item.AssemTypeName,
                    pid = item.Pid,
                    children = null
                };
                tree.children.Add(child);
                await Getchildren(item.AssemTypeId, child);
            }
        }
    }
}
